package com.noopsyche.optimization.utils;


/**
 * 十进制转化为二进制
 */
public class DoubleToBinary {

    private String zf;
    private int size = 7;

    /**
     * double类型转化为二进制
     * @param a
     * @return
     * @throws Exception
     */
    public String getDoubleToBinary(double a) throws Exception {
        if (a < 0.) {
            a = Math.abs(a);
            zf = "1_";
        }
        else {
            zf = "0_";
        }
        // 取整数部分
        int integral = (int) a;
        // 取小数部分
        double decimal = a - integral;
        // 整数转换二进制
        String integercom = toBinaryString(integral);
        String flocom = doubleToBinary(decimal, size);
        return integercom + flocom;
    }

    /**
     * 整数转化为二进制
     * @param n
     * @return
     */
    public String toBinaryString(int n) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(n % 2);
        n /= 2;
        while (n != 0) {
            stringBuilder.insert(0, n % 2);
            n = n / 2;
        }
        for (int i=stringBuilder.length(); i<8; i++) {
            stringBuilder.insert(0, 0);
        }
        return stringBuilder.toString();
    }

    /**
     * 小数转化为二进制
     * @param d
     * @param count
     * @return
     * @throws Exception
     */
    public String doubleToBinary(double d,int count) throws Exception{
        if (count>32){
            throw new Exception("The max bit must less than 32!");
        }
        if(count==0){
            throw new Exception("The min bit must bigger than 0");
        }
        double multi=0; //每次的乘积
        StringBuilder res=new StringBuilder();
        while(count>=0){
            multi=d*2;
            if(multi>=1){
                res.append(1);
                d=multi-1;
            }
            else{
                res.append(0);
                d=multi;
            }
            count--;
        }
        return res.toString();
    }

    /**
     * 将二进制小数转化为十进制
     * @param binXStr 二进制小数
     * @return 十进制小数
     */
    public static double bin2DecXiao(String binXStr){
        char[] decimal = binXStr.toCharArray();
        double decX = 0.0;
        int dex = 1;
        for (char i : decimal) {
            if (i == '0') {
                decX += 0 * Math.pow(2, -dex);
            }
            else {
                decX += 1 * Math.pow(2, -dex);
            }
            dex += 1;
        }
        return decX;
    }
}
